package com.zhanbo.zhanbowymusic.play;

import android.animation.ObjectAnimator;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.SeekBar;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.mwx.baselib.bean.LikeBean;
import com.mwx.baselib.bean.RanKingSongListBean;
import com.mwx.baselib.bean.SongBean;
import com.mwx.baselib.constant.Constant;
import com.mwx.baselib.net.AppConfig;
import com.mwx.baselib.net.BaseResponses;
import com.mwx.baselib.net.DefaultObserver;
import com.mwx.baselib.net.NetworkManager;
import com.mwx.baselib.utils.GlideUtils;
import com.mwx.baselib.utils.MLog;
import com.mwx.baselib.utils.SPUtils;
import com.zhanbo.zhanbowymusic.MainActivity;
import com.zhanbo.zhanbowymusic.R;
import com.zhanbo.zhanbowymusic.databinding.FragmentMusicPlayBinding;
import com.mwx.baselib.base.BaseFragment;
import com.zhanbo.zhanbowymusic.music.MusicController;
import com.zhanbo.zhanbowymusic.music.OnEvent;
import com.zhanbo.zhanbowymusic.play.bean.LikeEvBean;
import com.zhanbo.zhanbowymusic.play.view.LrcView;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

/**
 * 播放音乐页面
 */
public class MusicPlayFragment extends BaseFragment<FragmentMusicPlayBinding> implements View.OnClickListener {

    /**
     *播放器
     */
    /**
     * 更新歌词的频率，每100ms更新一次
     */
    private int mPlayerTimerDuration = 100;
    /**
     * 更新歌词的定时器
     */
    private Timer mTimer;
    /**
     * 更新歌词的定时任务
     */
    private TimerTask mTask;
    private RotateAnimation BoPianStartAnimation;
    private RotateAnimation BoPianPauseAnimation;
    private ObjectAnimator mAnimator;
    public static final int STATE_PLAYING = 1;//正在播放
    public static final int STATE_PAUSE = 2;//暂停
    public static final int STATE_STOP = 3;//停止
    private int mState;
    private List<SongBean> songs = new ArrayList<>();
    private int currentPosition;
    private int modeNum = 0;
    private List<Integer> modeList = new ArrayList<>();
    private MainActivity mainActivity;

    @Override
    protected Object getLayout() {
        return R.layout.fragment_music_play;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        mainActivity = (MainActivity) getActivity();
        initAnimation();
        initData();
        initListener();
        initView();
        setFragmentAnimator(new FragmentAnimator(R.anim.fragment_enter, R.anim.fragment_exit));
    }

    private void initAnimation() {
        mAnimator = ObjectAnimator.ofFloat(binding.ivHead, "rotation", 0.0f, 360.0f);
        mAnimator.setDuration(80000);//设定转一圈的时间
        mAnimator.setRepeatCount(Animation.INFINITE);//设定无限循环
        mAnimator.setRepeatMode(ObjectAnimator.RESTART);// 循环模式
        mAnimator.setInterpolator(new LinearInterpolator());// 匀速
        mAnimator.setStartDelay(10);

        //拨片开始播放动画
        BoPianStartAnimation = new RotateAnimation(35, 0, Animation.RELATIVE_TO_SELF, 0.1f, Animation.RELATIVE_TO_SELF, 0.25f);
        BoPianStartAnimation.setInterpolator(new LinearInterpolator());
        BoPianStartAnimation.setDuration(200); // 设置动画持续时间
        BoPianStartAnimation.setFillAfter(true); // 动画执行完后保持结束状态
        BoPianStartAnimation.setStartOffset(10);//执行前的等待时间
        //拨片暂停播放动画
        BoPianPauseAnimation = new RotateAnimation(0, 35, Animation.RELATIVE_TO_SELF, 0.1f, Animation.RELATIVE_TO_SELF, 0.25f);
        BoPianPauseAnimation.setInterpolator(new LinearInterpolator());
        BoPianPauseAnimation.setDuration(200); // 设置动画持续时间
        BoPianPauseAnimation.setFillAfter(true); // 动画执行完后保持结束状态
        BoPianPauseAnimation.setStartOffset(10);//执行前的等待时间

    }

    @Override
    protected void initData() {
        modeList.clear();
        modeList.add(R.mipmap.bofang_shunxu);
        modeList.add(R.mipmap.bofang_suiji);
        modeList.add(R.mipmap.bofang_danqu);
        modeNum = MusicController.musicController.getchangeMode();
        binding.ivMode.setImageResource(modeList.get(modeNum));
//从Controller类中获取歌曲数据
        List<SongBean> sheetData = MusicController.getInstance().getSheetData();
        songs.clear();
        songs.addAll(sheetData);
        //如果当前页面歌曲存在，更新第一次显示的歌曲信息
        if (songs.size() > 0) {

            currentPosition = MusicController.getInstance().getCurrentPosition();
            if (currentPosition < songs.size()) {
                binding.tvName.setText(songs.get(currentPosition).getName());
                binding.tvArtistName.setText("歌手：" + songs.get(currentPosition).getArtistName());
                binding.tvAlbumName.setText("专辑：" + songs.get(currentPosition).getAlbumName());
                GlideUtils.loadImage(_mActivity, songs.get(currentPosition).getCoverImg(), binding.ivHead);
                if (songs.get(currentPosition).getIsLike() == 1) {
                    binding.ivLike.setImageResource(R.mipmap.like);
                } else {
                    binding.ivLike.setImageResource(R.mipmap.like_no);
                }
                //进度条总长度
                int dt = MusicController.getInstance().getDuration();
                binding.seekbar.setMax(dt);
                initLyric();
            }
        }

        updateProgress();
        setAnimator();
    }

    private void initLyric() {

        binding.lrcView.loadLrcByUrl(AppConfig.URL + songs.get(currentPosition).getLyricUrl());
    }

    @Override
    protected void initView() {


    }

    @Subscribe
    public void getEvent(OnEvent event) {
        if (event.id == Constant.MUSIC_OVER) {//歌曲播放结束
            setAnimator();
//            binding.seekbar.setProgress(0);
        }
        if (event.id == 3) {
            currentPosition = MusicController.getInstance().getCurrentPosition();
            if (currentPosition < songs.size()) {
                binding.tvName.setText(songs.get(currentPosition).getName());
                binding.tvArtistName.setText("歌手：" + songs.get(currentPosition).getArtistName());
                binding.tvAlbumName.setText("专辑：" + songs.get(currentPosition).getAlbumName());
                GlideUtils.loadImage(_mActivity, songs.get(currentPosition).getCoverImg(), binding.ivHead);
                if (songs.get(currentPosition).getIsLike() == 1) {
                    binding.ivLike.setImageResource(R.mipmap.like);
                } else {
                    binding.ivLike.setImageResource(R.mipmap.like_no);
                }

                //进度条总长度
//                int dt = MusicController.getInstance().getDuration();
//                binding.seekbar.setMax(dt);
                initLyric();
            }

        }
        if (event.id == Constant.MUSIC_PLAY) {
            setAnimator();
        }
        if (event.id == Constant.MUSIC_PAUSE) {
            setAnimator();
        }
        if (event.id == Constant.MUSIC_MODE) {
            modeNum = MusicController.musicController.getchangeMode();
            binding.ivMode.setImageResource(modeList.get(modeNum));
        }


    }

    @Override
    protected void initListener() {
        binding.ivBack.setOnClickListener(this);
        binding.ivPlay.setOnClickListener(this);
        binding.ivLastOne.setOnClickListener(this);
        binding.ivNextOne.setOnClickListener(this);
        binding.ivMode.setOnClickListener(this);
        binding.ivPlayList.setOnClickListener(this);
        binding.ivLike.setOnClickListener(this);
        binding.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                MusicController.getInstance().seekTo(progress);
            }
        });

        binding.lrcView.setDraggable(true, new LrcView.OnPlayClickListener() {
            @Override
            public boolean onPlayClick(LrcView view, long time) {
                binding.lrcView.updateTime(time);
                MusicController.getInstance().seekTo((int) time);
                return false;
            }
        });
//        binding.lrcView.setOnPlayClickListener(new LrcView.OnPlayClickListener() {
//            @Override
//            public boolean onPlayClick(LrcView view, long time) {
//               MediaPlayerUtils.getInstance().seekTo((int) time);
//                return true;
//            }
//        });
    }

    public static MusicPlayFragment newInstance() {

        Bundle args = new Bundle();

        MusicPlayFragment  fragment = new MusicPlayFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        MLog.d("onDestroy()");
        MediaPlayerUtils.getInstance().destory();
    }

    private void setAnimator() {
        if (MusicController.getInstance().isPlaying) {
            if (mAnimator.isPaused()) {
                mAnimator.resume();//动画开始
            } else {
                mAnimator.start();
            }

            binding.ivHeiJiaoBoPian.startAnimation(BoPianPauseAnimation);
            binding.ivPlay.setImageResource(R.mipmap.bofangye_zanting);
        } else {
            mAnimator.pause();//动画暂停
            binding.ivPlay.setImageResource(R.mipmap.bofangye_bofang);
            binding.ivHeiJiaoBoPian.startAnimation(BoPianStartAnimation);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                pop();
                mHandler.removeMessages(1);
                mainActivity.showDockBar();
                break;
            case R.id.iv_play:
                if (MusicController.getInstance().isPlaying) {
                    MusicController.getInstance().pause();
                } else {
                    MusicController.getInstance().play();
                }
//                setAnimator();
                break;
            case R.id.iv_last_one:
                //上一曲
                MusicController.getInstance().lastOne();
                break;
            case R.id.iv_next_one:
                //下一曲
                MusicController.getInstance().nextOne();
                break;
            case R.id.iv_mode:
                modeNum++;
                if (modeNum > modeList.size() - 1) {
                    modeNum = 0;
                }
                binding.ivMode.setImageResource(modeList.get(modeNum));
                MusicController.getInstance().changeMode(modeNum);
                break;
            case R.id.iv_play_list:

                mainActivity.showPlayListDialog();
                break;
            case R.id.iv_like:

                like();
                break;
        }
    }

    private void like() {
        Map<String, String> map = new HashMap<>();
        map.put("targetId", songs.get(currentPosition).getId() + "");
        NetworkManager.getInstance().getApiService().songLike(map)
                .subscribeOn(Schedulers.io())
                .compose(this.bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new DefaultObserver<BaseResponses<LikeBean>>(_mActivity, false) {
                    @Override
                    public void onSuccess(BaseResponses<LikeBean> listBaseResponses) {

                    }

                    @Override
                    public void onNext(BaseResponses<LikeBean> likeBeanBaseResponses) {
                        if (likeBeanBaseResponses.getCode() == 200) {

                            if (likeBeanBaseResponses.getData() == null || "".equals(likeBeanBaseResponses.getData())) {
                                binding.ivLike.setImageResource(R.mipmap.like_no);
                                songs.get(currentPosition).setIsLike(0);

                                EventBus.getDefault().post(new LikeEvBean(songs.get(currentPosition).getId(), 0));
                            } else {
                                binding.ivLike.setImageResource(R.mipmap.like);
                                songs.get(currentPosition).setIsLike(1);

                                EventBus.getDefault().post(new LikeEvBean(songs.get(currentPosition).getId(), 1));

                            }
                        }

                    }
                });
    }

    private static final int INTERNAL_TIME = 500;// 音乐进度间隔时间

    // 每间隔1s通知更新进度
    private void updateProgress() {
        // 使用Handler每间隔1s发送一次空消息，通知进度条更新
        mHandler.sendEmptyMessageDelayed(1, INTERNAL_TIME);
    }

    /**
     * 进度条定时器
     */
    boolean isOne = true;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                // 展示给进度条和当前时间
                int currentDuration = MusicController.getInstance().getCurrentDuration();
                binding.seekbar.setProgress(currentDuration);
                MLog.e("isOne"+isOne);
                binding.lrcView.setOne(isOne);
                if (isOne){
                    isOne = false;
                }
                binding.lrcView.updateTime(currentDuration);
//                currentTime.setText(TimeUtil.parseTime(currentDuration));
                //Log.e("进度条定时器", "");
                // 继续定时发送数据
                updateProgress();

            }
            return true;

        }
    });


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}